package zookeeper.utils;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.yaml.snakeyaml.Yaml;

import java.io.InputStream;
import java.util.Collections;
import java.util.Map;

@Slf4j
public class YamlUtil {
  public static final Yaml reader = new Yaml();
  public static final String DEFAULT_FILENAME = "config.yaml";

  public static Map<String, Object> getMapFromYaml(String filename) {
    if (filename == null) {
      return Collections.emptyMap();
    }
    return reader.load(filename);
  }

  public static String getDefaultConnectStr() {
    ZookeeperObj config = getDefaultConfig();
    return config.getConnectStr();
  }

  public static String getDefaultClusterConnectStr() {
    ZookeeperObj config = getDefaultConfig();
    return config.getClusterConnectStr();
  }

  private static ZookeeperObj getDefaultConfig() {
    InputStream resourceAsStream = YamlUtil.class.getClassLoader().getResourceAsStream(DEFAULT_FILENAME);
    return reader.loadAs(resourceAsStream, ZookeeperObj.class);
  }

  @Data
  static class ZookeeperObj {
    public String localPort;
    public String wslIp;
    public String[] clusterConnectStr;

    String getConnectStr() {
      return wslIp + ":" + localPort;
    }

    String getClusterConnectStr() {
      StringBuilder sb = new StringBuilder();
      for (String s : clusterConnectStr) {
        sb.append(s);
        sb.append(",");
      }
      sb.deleteCharAt(sb.length() - 1);
      return sb.toString();
    }
  }
}
